﻿#include "stdafx.h"
#include "ChangeUserPwd.h"
#include "ui_ChangeUserPwd.h"

#include <QCryptographicHash>

ChangeUserPwd::ChangeUserPwd(QString username, QString userid, QString passwd, QWidget *parent) 
	: strUserName(username), strUserId(userid), strUserPwd(passwd), QDialog(parent), ui(new Ui::ChangeUserPwd)
{
	ui->setupUi(this);
	
	initUI();
}

ChangeUserPwd::~ChangeUserPwd()
{

}

void ChangeUserPwd::initUI()
{
	ui->leUserName->setText(strUserName);
	ui->leUserName->setReadOnly(true);
	ui->leUserName->setFrame(false);
	ui->leOldPwd->setEchoMode(QLineEdit::Password);
	ui->leNewPwd->setEchoMode(QLineEdit::Password);
	ui->leConfirmPwd->setEchoMode(QLineEdit::Password);
}

void ChangeUserPwd::on_btnChangePwd_clicked()
{
	QString sOldPwd = ui->leOldPwd->text();
	QString sNewPwd = ui->leNewPwd->text();
	QString sConfirmPwd = ui->leConfirmPwd->text();
	
	if (!check(sOldPwd))
	{
		qMsgBoxAlert(tr("Source password wrong!"));
		return;
	}

	changePwd(strUserId, sNewPwd, sConfirmPwd);
}

bool ChangeUserPwd::changePwd(QString userid, QString newpwd, QString confirmpwd)
{
	if (confirmpwd != newpwd)
	{
		qMsgBoxAlert(tr("Two times inputting are not same!"));
		return false;
	}

	QString strNewPasswd = getPasswdEncryptByMd5(newpwd);
	QString sqlUpdate = QString("UPDATE JXD7_XT_USER SET PASSWD = '%1' WHERE USERID = '%2'").arg(strNewPasswd).arg(userid);

	QString strError;
	bool bUpdate = execSQL(sqlUpdate, strError);

	if (bUpdate)
	{
		emit changePasswd(true);
		emit closeWidget();
		return true;
	} 
	else
	{
		qMsgBoxAlert(strError);
		emit changePasswd(false);
		return false;
	}
}

bool ChangeUserPwd::check(QString oldpwd)
{
	if (getPasswdEncryptByMd5(oldpwd).compare(strUserPwd, Qt::CaseInsensitive) == 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}

QString ChangeUserPwd::getPasswdEncryptByMd5(const QString strOriginal)
{
	QString strMd5;
	QByteArray bb;
	bb = QCryptographicHash::hash(strOriginal.toLocal8Bit(), QCryptographicHash::Md5);
	strMd5.append(bb.toHex().toUpper());
	
	return strMd5;
}
